//
//  CQEmoticonController.swift
//  表情键盘的搭建
//
//  Created by 陈乾 on 15/11/4.
//  Copyright © 2015年 陈乾. All rights reserved.
//  表情控制器 包含toolBar 和collectionView

import UIKit

class CQEmoticonController: UIViewController {
    
    
    //MARK: - 属性
    let ID = "item"
    
    var textView: UITextView?
    
    //MARK: - viewDidLoad
    override func viewDidLoad() {
        super.viewDidLoad()
        //准备UI
        prepareUI()
        
        
    }
    
    //MARK: - 准备UI
    func prepareUI() {
        
        //添加子控件
        
        view.addSubview(collectView)
        view.addSubview(toolBar)
        //添加约束
        
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        collectView.translatesAutoresizingMaskIntoConstraints = false
        
        
        let views = ["tb": toolBar, "cv": collectView]
        //因为这个东西 给别人用 最好不要用第三方来约束
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0),metrics: nil, views: views))
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0),metrics: nil, views: views))
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
        
        //设置toolBar
        setUpTabBar()
        
        //设置collectionview
        setUpCollectionView()
        
        
    }
    
    
    //基础tag
    let baseTag = 1000

    
    //MARK: -设置toolBar
    func setUpTabBar() {
        
        
        var itemArr = [UIBarButtonItem]()
        
        
        var index = 0
        for page in emoticonPackage
        {
            
            let packageName = page.group_name_cn
            let button = UIButton()
            
            //设置姓名
            button.setTitle(packageName, forState: UIControlState.Normal)
            button.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal)
            button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Highlighted)
            button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Selected)
            
            //添加点击事件
            button.addTarget(self, action: "itemClick:", forControlEvents: UIControlEvents.TouchUpInside)
            //设置tag
            button.tag = baseTag + index
            //自动选中第一个
            if index == 0 {
             setUpSelectedButton(button)
            }
            
            //tag自增
            index++
            
            //设置大小
            button.sizeToFit()
            //把按钮添加到customView里
            let item = UIBarButtonItem(customView: button)
            //把item都加进去
            itemArr.append(item)
            
            
            //添加弹簧
            itemArr.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
        }
        //取出多出一个弹簧
        itemArr.removeLast()
        toolBar.items = itemArr
        
    }
    
    //MARK: - toolBar上按钮的点击
    func itemClick(button: UIButton)
    {

      //根据tag - 1000 获取不同的组 在不同的组之间切换
       
        //创建一个indexPath: NSIndexPath
        let indexPath = NSIndexPath(forItem: 0, inSection: button.tag - baseTag)
        //选中collectionView的tag - 1000对应组
        collectView.selectItemAtIndexPath(indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition.Left)
         //选中
        setUpSelectedButton(button)
        
    }
    
    //记录已经选中的button
    var seletedButton: UIButton?
    
    
    //MARK: - 高亮选中
    func setUpSelectedButton(button: UIButton)
    {
        //已经选中的取消选中
       seletedButton?.selected = false
       //传递进来的buton选中
        button.selected = true
        //
        seletedButton = button
    
    }
    
    
    //MARK: - 设置setUpCollectionView
    func setUpCollectionView() {
        
        //设置控制器为数据源的代理
        collectView.dataSource = self
        //设置代理
        collectView.delegate = self
        //注册
        collectView.registerClass(CQEmoticonCell.self, forCellWithReuseIdentifier: ID)
        
        
        collectView.backgroundColor = UIColor(white: 0.8, alpha: 1)
    }
    
    
    
    //MARK: - 懒加载
    ///创建collectView的表情view
    lazy var collectView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: CQCollectionViewFlowLayout())
    ///创建toolBar
    lazy var toolBar: UIToolbar = {
        let tb = UIToolbar()
        tb.backgroundColor = UIColor.purpleColor()
        return tb
        }()
    ///加载表情包
    lazy var emoticonPackage = CQEmoticonPackage.emoticonPackageArr
    
    
}

//数据源 扩展
extension CQEmoticonController: UICollectionViewDataSource,UICollectionViewDelegate {
    
    //分为三组 一个表情包为一组
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
       return self.emoticonPackage.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.emoticonPackage[section].emoticons?.count ?? 0
    }
    
    //返回cell
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ID, forIndexPath: indexPath) as! CQEmoticonCell
        
//        cell.backgroundColor = UIColor(red: CGFloat(arc4random_uniform(256)) / 255.0, green: CGFloat(arc4random_uniform(256)) / 255.0, blue: CGFloat(arc4random_uniform(256)) / 255.0, alpha: 1)
        ///获取表情模型
       let emoticon = emoticonPackage[indexPath.section].emoticons?[indexPath.item]
        //给cellemoticon属性赋值
        cell.emoticon = emoticon
        return cell
        
    }
    //MARK: -停止滚动调用
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        
        //获取当前的item 对应的indexPath
         let indexPath = collectView.indexPathsForVisibleItems().first
          print(indexPath?.section)
        
        //获取组对应的button
        
        let button = toolBar.viewWithTag((indexPath?.section)! + baseTag) as! UIButton
        
        //高亮选中
        setUpSelectedButton(button)
        
        
        
    }
    
    //MARK: - 点击cell调用
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        
        //获得表情模型
        let emoticon = emoticonPackage[indexPath.section].emoticons![indexPath.item]
        //插入表情到textView
        textView?.insertEmoticon(emoticon)
        
        //最近的组不参与
        if indexPath.section != 0 {
            //添加最近表情模型
            CQEmoticonPackage.addFavoriteEmoticon(emoticon)
            
        }
        
    }
    
    
    
/*end*/
}

//自定义键盘：
// 当控制器的view作为键盘时 只要在viewDidAppear的时候frame才重新计算

//继承流水布局
class CQCollectionViewFlowLayout: UICollectionViewFlowLayout {
    
    //MARK: -重新准备布局
    override func prepareLayout() {
        super.prepareLayout()
        //设置itemSize
        
        let width = (collectionView?.frame.width)! / 7.0
        let heigth = (collectionView?.frame.height)! / 3.0
        itemSize = CGSize(width: width, height: heigth)
        
        //水平滚动
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        //不要间距
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        
        //取消弹簧效果
        collectionView?.bounces = false
        //分页
        collectionView?.pagingEnabled = true
        
        collectionView?.showsHorizontalScrollIndicator = false
        
        
    }
    
    
}


///自定义cell
class CQEmoticonCell: UICollectionViewCell {
    
    
    //MARK: - 表情模型
    var emoticon: CQEmoticon? {
        didSet{
            if let pngPath = emoticon?.pngPath {
             //给按钮设置图片
                CQEmoticonButton.setImage(UIImage(contentsOfFile: pngPath), forState: UIControlState.Normal)
            }else {
            //防止cell复用  没有就设置为空
                CQEmoticonButton.setImage(nil, forState: UIControlState.Normal)
            }
            //设置emoji图片
            CQEmoticonButton.setTitle(emoticon?.emoji, forState: UIControlState.Normal)
            if emoticon!.removeEmoticon {
            CQEmoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
            }
        }
    }
    
    //MARK: - 构造函数
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }
    
    
    private func prepareUI() {
        
        contentView.addSubview(CQEmoticonButton)
        
        //禁止用户点击
        CQEmoticonButton.userInteractionEnabled = false
        
        //设置frame
        CQEmoticonButton.frame = CGRectInset(self.bounds, 4, 4)
        CQEmoticonButton.backgroundColor = UIColor(white: 0.8, alpha: 1)
        CQEmoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        
    }
    
    //MARK: - 每一个item是一个按钮  即每一个表情是按钮
    private lazy var CQEmoticonButton: UIButton = UIButton()
    
    
}


